package cn.ultrarisk.scadmin.manager.biz.common.valid;

import cn.ultrarisk.scadmin.manager.biz.common.dao.DictDAO;
import cn.ultrarisk.scadmin.manager.biz.common.entity.Dict;
import cn.ultrarisk.scadmin.manager.exception.BizCheckedException;
import cn.ultrarisk.scadmin.manager.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * DictValidator
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/5/29
 * @since V1.0
 */
@Component
public class DictValidator {
    @Autowired
    private DictDAO dictDAO;

    public void validName(String name, boolean duplicate, Integer idNo) {
        if (StringUtil.isEmpty(name)) {
            throw new BizCheckedException("the name can't be empty");
        }
        if (duplicate) {
            if (dictDAO.getByName(name, idNo) != null) {
                throw new BizCheckedException("the name was duplicate");
            }
        }
    }

    public void validType(String type) {
        if (type == null) {
            throw new BizCheckedException("the type can't be null");
        }
        if (!Dict.TYPE_ALL.contains(type)) {
            throw new BizCheckedException("the type was wrong");
        }
    }

    public void validValue(String type, String value) {
        try {
            if (Dict.TYPE_BOOLEAN.equals(type)) {
                Boolean.parseBoolean(value);
            } else if (Dict.TYPE_INT.equals(type)) {
                Integer.parseInt(value);
            } else if (Dict.TYPE_LONG.equals(type)) {
                Long.parseLong(value);
            } else if (Dict.TYPE_DOUBLE.equals(type)) {
                Double.parseDouble(value);
            }
        } catch (Exception e) {
            throw new BizCheckedException("the type and value was mismatch");
        }
    }

    public void validLevel(Integer level) {
        if (level == null) {
            throw new BizCheckedException("the level can't be null");
        }
        if (!Dict.LEVEL_ALL.contains(level)) {
            throw new BizCheckedException("the type was wrong");
        }
    }

    public void validDelete(Integer id) {
        Dict dict = dictDAO.get(id);
        if (Dict.LEVEL_SYSTEM.equals(dict.getLevel())) {
            throw new BizCheckedException("the system level of dict can't be delete");
        }
    }
}
